
import 'package:flutter/material.dart';
import 'package:untitled/core/utils/navigate_to.dart';
import 'package:untitled/pages/home/add_friend/add_friend.dart';
import 'package:untitled/pages/profile/profile_main_page.dart';

import '../core/comments/custom_app_bar.dart';
import '../core/comments/popup.dart';
import '../core/socket/socket_service.dart';
import '../core/utils/toast.dart';
import 'home/home_page.dart';

class MainPage extends StatefulWidget {
  const MainPage({super.key});
  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  int _idx = 0;
  final _pages = [const HomePage(), const ProfileMainPage()];
  final GlobalKey _searchKey = GlobalKey();

  void _showPopup() {
    final RenderBox renderBox = _searchKey.currentContext!.findRenderObject() as RenderBox;
    final Offset position = renderBox.localToGlobal(Offset.zero);
    final Size size = renderBox.size;
    Popup.show(
      position: Offset(position.dx, position.dy + size.height),
      items: [
        PopupItem(icon: Icons.messenger, text: '发起群聊', onTap: () {
          toast('暂未开发');
        }),
        PopupItem(icon: Icons.person_add_alt_1, text: '添加朋友', onTap: () => navigateTo(const AddFriendPage())),
      ],
    );
  }
  @override
  void initState() {
    super.initState();
    SocketService().init(forceRefreshToken: false);
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title: const Text(
          'I M',
          style: TextStyle(fontSize: 17, fontWeight: FontWeight.w600),
        ),
        right: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: (){

              },
            ),
            IconButton(
              key: _searchKey,
              icon: const Icon(Icons.add),
              onPressed: _showPopup,
            ),
          ],
        ),
        showBottomLine: true,
      ),
      body: IndexedStack(index: _idx, children: _pages),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _idx,
        onTap: (i) => setState(() => _idx = i),
        items: const [
          BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),
          BottomNavigationBarItem(icon: Icon(Icons.person), label: '我的'),
        ],
      ),
    );
  }
}
